package com.cloudree.gllib.shape;

import android.opengl.GLES20;

import com.cloudree.gllib.BaseApp;
import com.cloudree.gllib.R;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * Created by Administrator on 2017/8/7.
 */
public class Line extends Shape {
    static float[] positionData = {
            -0.8f, 0.8f, 0.0f,
            -0.8f, -0.8f, 0.0f,
            0.8f, -0.8f, 0.0f,
    };

    static float[] colorData = {
            1.0f, 0.0f, 0.0f, 1.0f,
            0.0f, 1.0f, 0.0f, 1.0f,
            0.0f, 0.0f, 1.0f, 1.0f,
    };

    private FloatBuffer positionBuffer;
    private FloatBuffer colorBuffer;

    @Override
    public void loadingMaterial() {
        positionBuffer = ByteBuffer.allocateDirect(positionData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().put(positionData);
        positionBuffer.position(0);
        colorBuffer = ByteBuffer.allocateDirect(colorData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().put(colorData);
        colorBuffer.position(0);
    }

    @Override
    public void compileShader() {
        int vertexShader = generateShader(GLES20.GL_VERTEX_SHADER, getVertexShaderCode());
        int fragmentShader = generateShader(GLES20.GL_FRAGMENT_SHADER, getFragmentShaderCode());
        String[] attrs = new String[]{"aPosition", "aColor"};
        mProgram = generateGlProgram(vertexShader, fragmentShader, attrs);
    }

    @Override
    public void draw(float[] mvpMatrix, float[] modelMatrix, float[] viewMatrix, float[] projectionMatrix) {
        GLES20.glUseProgram(mProgram);
        int mvpMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        int positionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
        int colorHandle = GLES20.glGetAttribLocation(mProgram, "aColor");

        //allocate drawing order
        positionBuffer.position(0);
        GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 0, positionBuffer);
        GLES20.glEnableVertexAttribArray(positionHandle);
        colorBuffer.position(0);
        GLES20.glVertexAttribPointer(colorHandle, 4, GLES20.GL_FLOAT, false, 0, colorBuffer);
        GLES20.glEnableVertexAttribArray(colorHandle);

        GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);
        GLES20.glDrawArrays(GLES20.GL_LINES,0, 2);
    }

    @Override
    public String getVertexShaderCode() {
        return readRawFile(BaseApp.getApp(), R.raw.line_vertex_shader);
    }

    @Override
    public String getFragmentShaderCode() {
        return readRawFile(BaseApp.getApp(), R.raw.line_fragment_shader);
    }
}
